package com.aq.sales.business.impl;

import java.util.List;

import org.hibernate.Query;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.aq.sales.business.intf.QuoteBO;
import com.aq.sales.entity.QuoteItem;
import com.aq.sales.entity.User;
import com.aq.sales.entity.Quote;
@Service
@Transactional(propagation=Propagation.SUPPORTS, readOnly=true)
public class QuoteBOImpl extends CommonBOImpl<Quote> implements QuoteBO<Quote> {

		@Override
	public List<Quote> findAll(int accId) {
		Query qry=getCurrentSession().createQuery("from Quote where accId=:accId");
		qry.setInteger("accId", accId);
		return qry.list();
	}
	

	@Override
	public int insert(Quote obj) {
		throw new RuntimeException("This method is not Supported");
	}

	@Override
	@Transactional
	public int update(Quote obj) {
		throw new RuntimeException("This method is not Supported");
	}

	@Override
	public int delete(Quote obj) {
		getCurrentSession().delete(obj);
		return 0;
	}


	@Override
	public Quote findById(int id) {
		throw new RuntimeException("This method is not Supported");
	}

	@Override
	public Quote findById(int id, int accId) {
		Query qry=getCurrentSession().createQuery("from Quote where id=:id AND accId=:accId");
		qry.setInteger("id", id);
		qry.setInteger("accId", accId);
		return (Quote)qry.uniqueResult();
	}
	
	@Override
	public List<Quote> query(String where,int accId) {
		String sql="from Quote where "+where+" AND accId=:accId";
		Query qry=getCurrentSession().createQuery(sql);
		qry.setInteger("accId", accId);
		return qry.list();
	}


	@Override
	@Transactional
	public int insert(Quote c, List<QuoteItem> items) {
		getCurrentSession().save(c);
		for(QuoteItem qi:items){
			getCurrentSession().save(qi);
		}
		return 0;
	}
	@Override
	@Transactional
	public int update(Quote c, List<QuoteItem> items) {
		getCurrentSession().saveOrUpdate(c);
		for(QuoteItem qi:items){
			getCurrentSession().saveOrUpdate(qi);
		}
		return 0;
	}
	
	@Override
	@Transactional
	public int delete(Quote c, List<QuoteItem> items) {
		getCurrentSession().delete(c);
		for(QuoteItem qi:items){
			getCurrentSession().delete(qi);
		}
		return 0;
	}


	@Override
	public List<QuoteItem> getQuoteItems(int qid, int accId) {
		String sql="from QuoteItem where quote_id=:qid AND accId=:accId";
		Query qry=getCurrentSession().createQuery(sql);
		qry.setInteger("qid", qid);
		return qry.list();
	}
}
